package com.vhall.component.plugin.core.service;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.vhall.component.framework.oss.client.OssClient;
import com.vhall.component.framework.oss.client.OssClientFactory;
import com.vhall.component.framework.oss.client.OssResult;
import com.vhall.component.framework.oss.properties.OssProperties;
import com.vhall.component.plugin.common.config.OssSettings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 云对象存储
 *
 * @author yongzheng.xu
 * @since 2021/5/22 18:58
 */
@Slf4j
@Service
public class OssService {

    @Resource
    private OssClientFactory ossClientFactory;

    @Autowired
    private OssSettings settings;


    @PostConstruct
    public void initClients() {
        List<OssProperties> propertiesList = settings.getConf();
        propertiesList.forEach(prop -> ossClientFactory.createOrUpdateClient(prop));
    }


    /**
     * 上传到OSS服务器
     *
     * @param stream 文件流
     * @param name   文件名称 包括后缀名
     * @param type   文件imei
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String upload(InputStream stream, String name, String type) {
        OssClient client = ossClientFactory.getClient(settings.getType());
        //防止 上传的文件里面包含 特殊字符  特殊字符会导致oss 文件无法访问
        String regEx = "[`~!@#$%^&*()\\-+={}':;,\\[\\]<>?￥%…（）_+|【】‘；：”“’。，、？\\s]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(name);
        name = m.replaceAll("");
        OssResult<String> result = client.upload(name, type, stream);
        return result.getData();
    }


    /**
     * 上传到OSS服务器
     *
     * @param file 文件
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String upload(MultipartFile file) {
        String name = IdUtil.fastSimpleUUID();
        String ext = FileNameUtil.extName(file.getOriginalFilename());
        name = name + "." + ext;
        final String contentType = file.getContentType();
        try {
            return upload(file.getInputStream(), name, contentType);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
